$(document).ready(function () {
    var list = $('#List');
    $('.xh-datagrid-toolbar').parseToolbar();
    $('.xh-form').parseForm($('#bt_form_add, #bt_form_edit'));
    /*初始化列表*/
    var assistId = getQueryString('assistId');
    var taskId = getQueryString('taskId');
    console.log(assistId);
    console.log(taskId);
    /**************安装应用列表**********************/
    list.initDataGrid(moduleUrl + 'Service/getApps?assistId=' + assistId + '&taskId=' + taskId);
    //刷新获取应用列表
    var flag = false;

    var flash = setInterval(function flashRow() {
        // console.log(flag);
        //如果有执行中的任务 刷新
        // if (flag) {
        list.dataGridReload();
        flashTaskStatus(assistId, taskId, function (data) {
            if (data.state < 4) {
                flag = true;
            } else {
                flag = false;
                clearInterval(flash);
            }
        })
        // }
    }, 1000);
    //获取任务状态

    /**************卸载选中应用**********************/
    $('#btn_uninstall_app').click(function uninstallApp() {
        var row = list.datagrid('getSelected');
        if (row === null) {
            alert("未选中应用");
        }
        if (row !== null && row.packageName !== '') {
            // console.log(row.name);
            var packageName = row.packageName;
         if(confirm("确认卸载"+row.appName+"? " +
                 "卸载系统应用会导致异常")){
             var packageName = row.packageName;
             $('#uninstall_app_status').text('正在执行');
             //卸载指定应用
             var instruction = 'unInstallApp("' + packageName + '")';
             distributeTask(assistId, instruction, function (taskId) {
                 console.log('uninstall app start');
                 $('#btn_uninstall_app').hide();
                 var upload = setInterval(function uploadStatus() {
                     // console.log("flash upload");
                     flashTaskStatus(assistId, taskId, function (data) {
                         $('#uninstall_app_status').text('正在执行');
                         if (data.state === 4) {
                             $('#uninstall_app_status').text('操作成功');
                             clearInterval(upload);
                             //进入新目录
                             entryInstalledAppList('', assistId);
                         } else if (data.state === 5) {
                             $('#uninstall_app_status').text('操作超时');
                             clearInterval(upload);
                         }
                     });
                 }, 1000);
             });
         }
        }
    });


    /**************抓取应用日志**********************/
    $('#btn_catch_app_log').click(function () {
        var row = list.datagrid('getSelected');
        if (row === null) {
            alert("未选中应用");
        }
        if (row !== null && row.packageName !== '') {
            // console.log(row.name);
            var packageName = row.packageName;
            $('#catch_app_log_status').text('正在执行');
            var instruction = 'startCatchLog("' + packageName + '")';

            distributeTask(assistId, instruction, function (taskId) {
                $('#btn_catch_app_log').hide();
                var upload = setInterval(function () {
                    flashTaskStatus(assistId, taskId, function (data) {
                        $('#catch_app_log_status').text('正在执行');
                        if (data.state === 4) {
                            $('#catch_app_log_status').text('操作成功');
                            clearInterval(upload);
                            $('#btn_catch_app_log').show();
                            //进入新目录
                        } else if (data.state === 5) {
                            $('#catch_app_log_status').text('操作超时');
                            clearInterval(upload);
                            $('#btn_catch_app_log').show();
                        }
                    })

                },1000)
            })
        }
    });

    /**************停止抓取应用日志并上传**********************/
    $('#btn_stop_catch_app_log').click(function () {
        var row = list.datagrid('getSelected');
        if (row === null) {
            alert("未选中应用");
        }
        if (row !== null && row.packageName !== '') {
            // console.log(row.name);
            var packageName = row.packageName;
            $('#btn_stop_catch_app_log').hide();
            $('#stop_catch_app_log_status').text('正在执行');
            var instruction = 'stopCatchLog("' + packageName + '")';

            distributeTask(assistId, instruction, function (taskId) {
                $('#btn_stop_catch_app_log').show();
                $('#catch_app_log_url').text('');
                var upload = setInterval(function () {
                    flashTaskStatus(assistId, taskId, function (data) {
                        // $('#stop_catch_app_log_status').text('正在执行');
                        if (data.state === 4) {
                            $('#stop_catch_app_log_status').text('操作成功');
                            // clearInterval(upload);
                            //进入新目录
                        } else if (data.state === 6) {
                            clearInterval(upload);
                            $('#stop_catch_app_log_status').text('返回结果');
                            var resource = data.resources[0];
                            // console.log(resource);
                            var url = resource.url;
                            // console.log(url);
                            $("#catch_app_log_url").attr("href", url);
                            $('#catch_app_log_url').text(url);

                            $('#catch_app_log_url');
                        } else if (data.state === 5) {
                            $('#stop_catch_app_log_status').text('操作超时');
                            clearInterval(upload);
                        }
                    })

                },1000)
            })
        }
    });

    /**************安装上传应用**********************/
    $('#btn_upload_file').click(function () {
        $('#upload_file_input').click();

    });

    $('#upload_file_input').change(function () {

        console.log('选择文件');
        if ($('#upload_file_input')[0].files.length) {
            var list = $('#upload_file_input')[0].files;
            var name = list[0].name;
            if (!name.endWith('apk')) {
                alert('所选文件并非应用');
            }
            if (name.endWith('apk')) {
                if (confirm("确定安装应用:" + name + "?")) {
                    $('#btn_upload_file').hide();
                    var url = 'http://files.yunzuoye.net/XHFileServer/file/upload/xhtest/';
                    uploadFile(url, list[0], function (result) {
                        result = JSON.parse(result);
                        if (result.status === 1000) {
                            console.log(result);
                            $('#trans_file_state').text('上传文件服务器成功');
                            var fileUrl = result.uploadFileDTO.fileId;
                            //    下发任务
                            $('#btn_upload_file').show();
                            $('#trans_file_state').text('下发任务');
                            var instruction = 'installAppOnline("' + fileUrl + '")';
                            distributeTask(assistId, instruction, function (taskId) {
                                var upload = setInterval(function uploadStatus() {
                                    // console.log("flash upload");
                                    flashTaskStatus(assistId, taskId, function (data) {
                                        // checkTranslate(data);
                                        $('#trans_file_state').text('传输中');
                                        if (data.state === 4) {

                                            $('#trans_file_state').text('操作成功 正在安装');
                                        } else if (data.state === 6) {
                                            $('#trans_file_state').text('操作成功');
                                            clearInterval(upload);
                                            //刷新当前目录
                                            entryInstalledAppList("", assistId);
                                        } else if (data.state === 5) {
                                            $('#trans_file_state').text('操作超时');
                                            clearInterval(upload);
                                        }
                                    });
                                }, 1000);
                            })
                        } else {
                            $('#trans_file_state').text('上传文件服务器失败');
                            alert(result.message);
                        }
                    });
                }
            }
        } else {
            // $(this).parent().next().html("未上传任何文件");
        }

    });

    /**************清除防火墙**********************/
    $('#btn_clear_firewall').click(function () {

            $('#clear_firewall_status').text('正在执行');
            var instruction = 'clearFirewall()';

            distributeTask(assistId, instruction, function (taskId) {
                $('#btn_clear_firewall').hide();
                var upload = setInterval(function () {
                    $('#btn_clear_firewall').show();
                    flashTaskStatus(assistId, taskId, function (data) {
                        $('#clear_firewall_status').text('正在执行');
                        if (data.state === 4) {
                            $('#clear_firewall_status').text('操作成功');
                            clearInterval(upload);
                            //进入新目录
                        } else if (data.state === 5) {
                            $('#clear_firewall_status').text('操作超时');
                            clearInterval(upload);
                        }
                    })

                },1000)
            })

        }
    );

    /**************清除应用数据**********************/
    $('#btn_clear_app_data').click(function () {
            var row = list.datagrid('getSelected');
            if (row === null) {
                alert("未选中应用");
            }
            if (row !== null && row.packageName !== '') {
                var packageName = row.packageName;
                //平台包名
                if (packageName === 'com.xuehai.response_launcher_teacher' || packageName === 'com.xuehai.launcher') {
                    alert('无法清除平台数据');
                }else {
                    $('#clear_app_data_status').text('正在执行');
                    var instruction = 'clearAppData("' + packageName + '")';
                    $('#btn_clear_app_data').hide();
                    distributeTask(assistId, instruction, function (taskId) {

                        var upload = setInterval(function () {
                            $('#btn_clear_app_data').show();
                            flashTaskStatus(assistId, taskId, function (data) {
                                if (data.state === 4) {
                                    $('#clear_app_data_status').text('操作成功');
                                    clearInterval(upload);
                                    //进入新目录
                                } else if (data.state === 5) {
                                    $('#clear_app_data_status').text('操作超时');
                                    clearInterval(upload);
                                }
                            })

                        },1000)
                    });
                }
            }

        }
    );


    /**************协助状态**********************/
        //定时获取协助是否存活
    var alive = setInterval(function getAssistAlive() {
            getAliveAssist(assistId, $('#device_alive'),function () {
                $('#bt_Task_Add').setButtonDisable('eu');
                $('#assist_quit').attr('hidden', 'hidden');
                clearInterval(alive);
            });
        }, 5000);
    //获取协助状态
    var text = $('#assist_state').text();
    var state = getState(text);
    /*    if (state === '准备' || state === '进行中') {
     getAliveAssist(id);
     }*/
    if (state === '完成' || state === '超时') {
        $('#bt_Task_Add').setButtonDisable('eu');
        $('#assist_quit').attr('hidden', 'hidden');
        clearInterval(alive);
        // clearInterval(flash);
    }
    //退出协助
    $('#assist_quit').click(function () {
        assistQuit(assistId,function () {
            $('#assist_quit').attr('hidden', 'hidden');
            location.reload();
        })

    });
    $('#bt_form_back').click(function () {
        $.overtFun.clickBackForm();
    });
    $('#bt_form_reset').click(function () {
        $.overtFun.clickResetForm();
    });

});

//获取协助状态
function getState(text) {
    if (text !== null || text.length !== 0) {
        var array = text.split('：');
        // console.log(array);
        return array[1];
    }
}

function entryInstalledAppList(title, assistId) {
    // 下发目录指令
    //初始目录
    var instruction = 'getInstallAppList()';
    // console.log(instruction);
    distributeTask(assistId, instruction, function (taskId) {
        //打开目录页面
        var catalogUrl = moduleUrl + "assist/apps?assistId=" + assistId + "&taskId=" + taskId;
        console.log(catalogUrl);
        /* if (title !== '') {
         window.top.xhTop.createNewTab(title, catalogUrl);
         } else {*/
        // console.log('打开网页');
        window.location.href = catalogUrl;
        // }

    });

}

